package com.example.smartrefreshlayoutdemo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import java.util.HashMap;
import java.util.Map;

import static android.R.id.widget_frame;

@SuppressWarnings({"UnusedParameters","unused"})
public class FragmentActivity extends AppCompatActivity {
    protected static String EXTRA_FRAGMENT = "extra_fragment";
    private Fragment fragment;

    public static void start(Context context,Class<?> clazz,Object... params){
        if (context != null && Fragment.class.isAssignableFrom(clazz)) {
            context.startActivity(newIntent(context,clazz,params));
        }
    }

    public static void start(Activity activity,Class<?> clazz,Object... params){
        start((Context) activity, clazz, params);
    }

    public static void start(Fragment fragment,Class<?> clazz,Object... params){
        start((Context) fragment.getActivity(), clazz, params);
    }

    public static Intent newIntent(Context context,Class<?> clazz,Object... params){
        Intent intent = new Intent(context,FragmentActivity.class);
        intent.putExtra(EXTRA_FRAGMENT,clazz.getName());
        return intent;
    }

    protected String mFragmentClazz = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFragmentClazz = getIntent().getStringExtra(EXTRA_FRAGMENT);
        FrameLayout frameLayout = new FrameLayout(this);
        frameLayout.setId(widget_frame);
        setContentView(frameLayout);
        replaceFragment();
    }

    private void replaceFragment() {
        try {
            fragment = (Fragment) getFragmentClass().newInstance();
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(widget_frame,fragment);
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Map<String,Class> typeCache = new HashMap<>();
    private Class<?> getFragmentClass() throws ClassNotFoundException{
        Class type = typeCache.get(mFragmentClazz);
        if (type == null) {
            typeCache.put(mFragmentClazz,type = Class.forName(mFragmentClazz));
        }
        return type;
    }

    public Fragment getFragment(){
        return fragment;
    }
}
